package io.gitee.hejiang.action.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.WrapFactory;

public class ObjectWrapFactory extends WrapFactory {
	private static ObjectWrapFactory _inst = new ObjectWrapFactory();
	public static ObjectWrapFactory instance() {
		return _inst;
	}
	
	@Override
	public Object wrap(Context cx, Scriptable scope, Object obj, Class<?> staticType) {
		if (staticType == null) {
			staticType = obj != null ? obj.getClass() : Object.class;
		}

		if (staticType.isArray()) {
			Object[] array = Arrays.stream((Object[]) obj).map((item) -> Context.javaToJS(item, scope)).toArray();
			return cx.newArray(scope, array);
		} else if (List.class.isAssignableFrom(staticType)) {
			Object[] array = ((List<?>) obj).stream().map((item) -> Context.javaToJS(item, scope)).toArray();
			return cx.newArray(scope, array);
		} else if (Map.class.isAssignableFrom(staticType)) {
			Map<?, ?> map = (Map<?, ?>) obj;
			if (map.size() > 0 && map.keySet().iterator().next() instanceof String) {
				Scriptable ret = cx.newObject(scope);
				map.forEach((key, value) -> ret.put((String) key, ret, Context.javaToJS(value, scope)));
				return ret;
			}
		}

		return super.wrap(cx, scope, obj, staticType);
	}

}
